<template>
  <vxe-modal v-model="visibleRef" v-bind="getModalBindValue">
    <template #title v-if="!$slots.title">
      <ModalHeader
        :helpMessage="getMergeProps.helpMessage"
        :title="getMergeProps.title"
        @dblclick="handleTitleDbClick"
      />
    </template>

    <template #footer v-if="!$slots.footer">
      <ModalFooter v-bind="getBindValue" @ok="handleOk" @cancel="handleCancel">
        <template #[item]="data" v-for="item in Object.keys($slots)">
          <slot :name="item" v-bind="data || {}"></slot>
        </template>
      </ModalFooter>
    </template>

    <slot></slot>

    <template #[item]="data" v-for="item in Object.keys(omit($slots, ['default']))">
      <slot :name="item" v-bind="data || {}"></slot>
    </template>
  </vxe-modal>
</template>

<script setup lang="ts">
  import type { ModalProps, ModalMethods } from './typing'

  import { computed, ref, watch, unref, watchEffect, getCurrentInstance, useAttrs } from 'vue'
  import {
    onMountedOrActivated,
    onUnMountedOrDeactivated
  } from '@/composables/onMountedOrActivated'
  import { VxeModal } from 'vxe-pc-ui'
  import ModalFooter from './components/ModalFooter.vue'
  import ModalHeader from './components/ModalHeader.vue'
  import { merge, isFunction, omit } from 'xe-utils'

  defineOptions({
    inheritAttrs: false
  })

  const props = withDefaults(defineProps<ModalProps>(), {
    showFooter: true,
    destroyOnClose: true,
    showMaximize: true,
    showMinimize: false,
    mask: true,
    lockView: true,
    resize: true,
    remember: true,
    escClosable: true,
    beforeHideMethod: undefined,

    showOkBtn: true,
    showCancelBtn: true,
    okText: '确定',
    cancelText: '取消',
    okType: 'primary'
  })

  const attrs = useAttrs()

  const emits = defineEmits([
    'visible-change',
    'update:visible',
    'cancel',
    'ok',
    'register',
    'click-outside'
  ])

  const visibleRef = ref(false)
  const propsRef = ref<Partial<ModalProps> | null>(null)

  const modalMethods: ModalMethods = {
    setModalProps,
    emitVisible: undefined
  }

  const instance = getCurrentInstance()
  if (instance) {
    // console.log('modal初始化1');
    emits('register', modalMethods, instance.uid)
  }

  const getMergeProps = computed((): Recordable => {
    // console.log(props, 'BasicVxeModal-props');
    // console.log(attrs, 'BasicVxeModal-attrs');

    return {
      ...props,
      ...(unref(propsRef) as any)
    }
  })

  const getBindValue = computed((): ModalProps & Recordable => {
    const attr = {
      ...attrs,
      ...unref(getMergeProps)
    }
    return omit(attr, [''])
  })

  const getModalBindValue = computed((): Recordable => {
    const attr = {
      id: instance ? String(instance.uid) : undefined,
      ...attrs,
      ...unref(getMergeProps)
    }

    // 排除非modal属性
    return omit(attr, [
      'visible',
      'okText',
      'cancelText',
      'showOkBtn',
      'showCancelBtn',
      'okButtonProps',
      'cancelButtonProps',
      'okType',
      'confirmLoading',
      'helpMessage'
    ])
  })

  watchEffect(() => {
    visibleRef.value = !!props.visible
  })

  watch(
    () => unref(visibleRef),
    (v) => {
      emits('visible-change', v)
      emits('update:visible', v)
      instance && modalMethods.emitVisible?.(v, instance.uid)
    },
    {
      immediate: false
    }
  )

  // 取消事件
  async function handleCancel(e: Event) {
    e?.stopPropagation()
    // 过滤自定义关闭按钮的空白区域
    // if ((e.target as HTMLElement)?.classList?.contains(prefixCls + '-close--custom')) return
    if (props.beforeHideMethod && isFunction(props.beforeHideMethod)) {
      const isClose: boolean = await props.beforeHideMethod()
      visibleRef.value = !isClose
      return
    }

    visibleRef.value = false
    emits('cancel', e)
  }

  /**
   * @description: 设置modal参数
   */
  function setModalProps(props: Partial<ModalProps>): void {
    propsRef.value = merge(unref(propsRef) || ({} as any), props)
    if (Reflect.has(props, 'visible')) {
      visibleRef.value = !!props.visible
    }
  }

  function handleOk(e: Event) {
    emits('ok', e)
  }

  function handleTitleDbClick(e) {
    if (!props.showMaximize) return
    e.stopPropagation()
  }

  // todo: 点击弹窗外关闭弹窗 临时处理
  let visChange = false
  watch(
    () => visibleRef.value,
    (val) => {
      if (val) {
        visChange = true
      }
    }
  )

  function handleClickModalOut(event) {
    if (visChange) {
      // 忽略切换弹窗第一次点击事件
      visChange = false
      return
    }
    if (!unref(visibleRef)) return
    const target = event.target
    const isInsideModal = target && target.closest && target.closest('.vxe-modal--box') !== null
    if (!isInsideModal) {
      emits('click-outside')
      // console.log('在modal外点击');
    } else {
      // console.log('在modal内点击');
    }
  }

  onMountedOrActivated(() => {
    window.addEventListener('click', handleClickModalOut)
  })

  onUnMountedOrDeactivated(() => {
    window.removeEventListener('click', handleClickModalOut)
  })
</script>

<style lang="scss">
  .vxe-modal--wrapper {
    .vxe-modal--container {
      max-height: 100vh;
    }

    .vxe-modal--footer .ant-btn + .ant-btn:not(.ant-dropdown-trigger) {
      margin-bottom: 0;
      margin-left: 8px;
    }
  }
</style>
